package com.shop.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.WeChatCart.UserCartRemoveDto;
import com.shop.entity.dto.WeChatCart.UserCartSaveDto;
import com.shop.entity.dto.WeChatCart.UserCartUpdateNumDto;
import com.shop.entity.pojo.*;
import com.shop.entity.vo.CartVo;
import com.shop.user.mapper.*;
import com.shop.user.service.CartService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private CostMapper costMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result addCart(UserCartSaveDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        User checkUser = userMapper.selectById(userId);
        if (userId==null||checkUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        String k=Message.WeChat_Key_User_Cart+userId;
        redisTemplate.delete(k);
        Cart cart=new Cart();
        Cart checkCart = cartMapper.selectOne(Wrappers.<Cart>lambdaQuery()
                .eq(Cart::getUserId,userId)
                .eq(Cart::getWaresId,dto.getWaresId())
                .eq(Cart::getCostId,dto.getCostId()));
        if (checkCart==null) {
            Wares wares = waresMapper.selectById(dto.getWaresId());
            Style style = styleMapper.selectById(dto.getStyleId());
            Cost cost = costMapper.selectById(dto.getCostId());
            if (wares==null||style==null||cost==null) {
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }

            System.out.println(userId);
            cart.setUserId(userId);
            cart.setWaresName(wares.getWaresName());
            cart.setStyleName(style.getStyleName());
            cart.setCostPrice(cost.getWaresPrice());
            cart.setCostMessage(cost.getCostMessage());
            cart.setStyleImages(style.getStyleImages());
            cart.setWaresNumber(dto.getWaresNumber());
            cart.setWaresId(dto.getWaresId());
            cart.setStyleId(dto.getStyleId());
            cart.setCostId(dto.getCostId());
            int saveCart = cartMapper.insert(cart);
            if (saveCart==Message.Check_Int_False) {
                return Result.errorResult(Code.SERVER_ERROR);
            }
            redisTemplate.delete(k);
            return Result.okResult(Code.SUCCESS);
        }

        BeanUtils.copyProperties(checkCart,cart);
        cart.setWaresNumber(cart.getWaresNumber()+dto.getWaresNumber());
        int updateCart = cartMapper.updateById(cart);
        if (updateCart==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<List<CartVo>> getCart() {
        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        String k=Message.WeChat_Key_User_Cart+userId;
        List<Cart> check = (List<Cart>) redisTemplate.opsForValue().get(k);
        if (check!=null&&check.size()> Message.Check_Int_Null) {
            return Result.okResult(check);
        }
        List<Cart> v = cartMapper.selectList(Wrappers.<Cart>lambdaQuery().eq(Cart::getUserId,userId));
        redisTemplate.opsForValue().set(k,v,1, TimeUnit.HOURS);
        return Result.okResult(v);
    }

    @Override
    public Result updateCartNum(UserCartUpdateNumDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        User checkUser = userMapper.selectById(userId);
        if (userId==null||checkUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        String k=Message.WeChat_Key_User_Cart+userId;
        redisTemplate.delete(k);
        Cart oneCart = cartMapper.selectOne(Wrappers.<Cart>lambdaQuery()
                .eq(Cart::getUserId,userId)
                .eq(Cart::getId,dto.getCartId()));

        if (oneCart==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (oneCart.getWaresNumber()==Message.WeChat_Cart_Up&&dto.getNewNumber()==Message.WeChat_Cart_Down) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        int waresNumber=oneCart.getWaresNumber()+dto.getNewNumber();
        Cart cart=new Cart();
        cart.setCostPrice(oneCart.getCostPrice());
        cart.setWaresNumber(waresNumber);
        int updateCartNum = cartMapper.update(cart,Wrappers.<Cart>lambdaQuery().eq(Cart::getId,dto.getCartId()));
        if (updateCartNum== Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result delCart(UserCartRemoveDto dto) {
        if (dto==null||dto.getAllOrOne()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        boolean remove=false;
        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        String k=Message.WeChat_Key_User_Cart+userId;
        redisTemplate.delete(k);
        if (dto.getAllOrOne().equals("all")) {
            remove = remove(Wrappers.<Cart>lambdaQuery().eq(Cart::getUserId, userId));
            if (!remove) {
                return Result.errorResult(Code.SERVER_ERROR);
            }
            redisTemplate.delete(k);
            return Result.okResult(Code.SUCCESS);
        }else if (dto.getAllOrOne().equals("one")){
            Cart one = getOne(Wrappers.<Cart>lambdaQuery().eq(Cart::getId, dto.getCartId()).eq(Cart::getUserId,userId));
            if (one==null) {
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
           remove = remove(Wrappers.<Cart>lambdaQuery().eq(Cart::getId, dto.getCartId()).eq(Cart::getUserId, userId));
            if (!remove) {
                return Result.errorResult(Code.SERVER_ERROR);
            }
            redisTemplate.delete(k);

            return Result.okResult(Code.SUCCESS);
        }else {
            return Result.errorResult(Code.PARAM_INVALID);
        }

    }

}
